console.clear();

let baseURL = 'http://127.0.0.1:3002';

// 解析数据
function analysis() {
    let data = {}
    let issue = [], detail = [];
    document.getElementsByClassName('td-issue')[0].querySelectorAll('.issue-number').forEach((item) => {
        // console.log(item.innerHTML.trim())
        issue.push(Number(item.innerHTML.trim()))
    })
    document.getElementsByClassName('td-lottery-number-item')[0].querySelectorAll('.lottery-number').forEach((item) => {
        // console.log(item.innerText.trim().replaceAll(/\D/g, '').replaceAll('', '/'))
        detail.push(item.innerText.trim().replaceAll(/\D/g, '').replaceAll('', '/'))
    })
    issue.forEach((item, index) => {
        data[item] = baseURL + '/setData/' + item + detail[index];
    })
    // console.log('analysis:\n', data)
    return data;
}

function getLimit(fn) {
    fetch(baseURL + '/getLimit', {}).then(response => {
        if (response.status >= 200 && response.status < 300) { // 判断请求是否成功
            return response.json() // 得到 JSON 对象
        } else {
            throw new Error(response.statusText);
        }
    }).then(json => {
        console.log(json);  // 得到最终结果。
        fn && fn(json);
    }).catch(err => {
        console.log('获取数据失败：', err)
    });
}

function setData(url) {
    fetch(url, {}).then(response => {
        if (response.status >= 200 && response.status < 300) { // 判断请求是否成功
            return response.json() // 得到 JSON 对象
        } else {
            throw new Error(response.statusText);
        }
    }).then(json => {
        console.log(url + ":  " + json);  // 得到最终结果。
    }).catch(err => {
        console.log('设置数据失败：', err)
    });
}

setInterval(() => {
    // if (document.getElementsByClassName('td-issue').length == 0 || document.getElementsByClassName('td-lottery-number-item').length == 0) return
    if (location.hash != "#/trend/16") return;

    let analysisData = analysis();
    getLimit((res) => {
        Object.keys(analysisData).forEach((item) => {
            if (!res.includes(Number(item))) {
                setData(analysisData[item]);
            }
        })
    })

    setTimeout(() => {
        // 刷新数据
        document.getElementsByClassName('issue')[0].children[0].click();
    }, 5000);
}, 20 * 1000);

window.alert = function (data) {
    console.log('alert ===  ', data)
}